package org.webshop.frontend.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.webshop.backend.data.Product;
import org.webshop.backend.dbchif.DbAccess;
import org.webshop.frontend.servlets.util.ServletUtil;

@WebServlet("/admin/products/add")
public class ProductAddServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * Serve the system manager a view for adding a product
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletUtil.forwardToView(request, response, "addProduct");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String designation = request.getParameter("designation");
        String url = request.getParameter("url");
        double price = Double.parseDouble(request.getParameter("price"));

        if (designation == null || designation.isEmpty()) {
            ServletUtil
                .showGeneralError("The designation of the product must not be null or empty!", request, response);
            return;
        }

        if (url == null || url.isEmpty()) {
            ServletUtil.showGeneralError("The url of the product must not be null of empty", request, response);
            return;
        }

        if (price <= 0) {
            ServletUtil.showGeneralError("The price must not be negative", request, response);
            return;
        }

        Product product = new Product(designation, url, price);
        DbAccess dbAccess = DbAccess.getInstance();
        dbAccess.addProduct(product);
    }
}
